﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace hmc.im.service.core
{
    public static class CommandBusiness
    {
        /// <summary>
        /// 命令处理
        /// </summary>
        /// <param name="commandText"></param>
        /// <returns></returns>
        public static CommandResultEntity Execute(string commandText, string remoteEndPoint)
        {
            if (string.IsNullOrEmpty(commandText)) throw new ArgumentNullException("未知的命令，命令不能为空");
            string[] commands = commandText.Split('|');
            if (commands.Length != 2) throw new ArgumentException("未知的命令，合格的命令格式为int|string");
            int commandType = -1;
            if (int.TryParse(commands[0], out commandType) == false) throw new ArgumentException("未知的命令，commandtype is not int");

            CommandResultEntity resultEntity = new CommandResultEntity();

            switch (commandType)
            {
                case (int)EnumDirectiveType.Login:
                    resultEntity = ExecuteLoginCommand(commands[1], remoteEndPoint);
                    break;
                case (int)EnumDirectiveType.HandClasp:
                    resultEntity = ExecuteHandClaspCommand(commands[1], remoteEndPoint);
                    break;
                case (int)EnumDirectiveType.Logout:
                    resultEntity = ExecuteLogoutCommand(commands[1], remoteEndPoint);
                    break;
                case (int)EnumDirectiveType.Hint:

                    break;
            }
            return resultEntity;
        }

        /// <summary>
        /// 握手
        /// </summary>
        /// <param name="commandText"></param>
        /// <returns></returns>
        private static CommandResultEntity ExecuteHandClaspCommand(string commandText, string remoteEndPoint)
        {
            CommandResultEntity resultEntity = new CommandResultEntity();
            resultEntity.CommandType = EnumDirectiveType.HandClasp;
            string username = commandText.Split(',')[0];
            var q = (from p in UserAccessTokenDB.DB where p.UserName == username select p).SingleOrDefault();
            if (q == null || q.RemoteEndPoint != remoteEndPoint)
            {
                resultEntity.Status = false;
                resultEntity.Message = "Login TimeOut";
            }
            else
            {
                q.LastCcommunication = DateTime.Now;
                resultEntity.Status = true;
                resultEntity.Message = "Success";
                resultEntity.UserAccessToken = q;
            }
            return resultEntity;
        }

        /// <summary>
        /// 登录处理
        /// </summary>
        /// <param name="commandText"></param>
        /// <returns></returns>
        private static CommandResultEntity ExecuteLoginCommand(string commandText, string remoteEndPoint)
        {
            CommandResultEntity resultEntity = new CommandResultEntity();
            resultEntity.CommandType = EnumDirectiveType.Login;

            string[] userInfo = commandText.Split(',');
            systemuserLogic user = new systemuserLogic();
            systemuserEntity userEntity = user.GetUser(userInfo[0]);
            string inputpwd = CipherHelper.Hash(userInfo[1], CipherHelper.HashFormat.MD532).ToLower();

            if (userEntity == null)
            {
                resultEntity.Status = false;
                resultEntity.Message = "UserNotExist";
                //sendMSG = (int)EnumDirectiveType.Login + "|false,UserNotExist";
                //Logger.Writer("客户端" + userInfo[0] + "用户名不存在");
            }
            else if (userEntity.Password != inputpwd)
            {
                resultEntity.Status = false;
                resultEntity.Message = "PasswordError";
                //sendMSG = (int)EnumDirectiveType.Login + "|false,PasswordError";
                //Logger.Writer("客户端" + userInfo[0] + "密码错误");
            }
            else
            {

                resultEntity.Status = true;


                //Console.WriteLine("客户端" + commandText[0] + "连接成功");
                //Logger.Writer("客户端" + commandText[0] + "连接成功");

                string accessToken = CipherHelper.Hash(commandText[0] + "," + commandText[2], CipherHelper.HashFormat.MD532).ToLower();//组合AccessToken

                UserAccessTokenEntity userAccessTokenEntity = new UserAccessTokenEntity { UserId = userEntity.UserId, UserName = userInfo[0], Password = userInfo[1], IP = userInfo[2], LastCcommunication = DateTime.Now, AccessToken = accessToken, LoginTime = DateTime.Now, LastExitTime = userEntity.LastExitTime, LastLoginTime = userEntity.LastLoginTime, RemoteEndPoint = remoteEndPoint };

                //添加用户到列表
                UserAccessTokenDB.DB.Add(userAccessTokenEntity);

                resultEntity.Message = accessToken;
                resultEntity.UserAccessToken = userAccessTokenEntity;

                //更新登录状态
                user.UpdateUserLoginStatus(userEntity.UserId, userInfo[2]);


            }
            return resultEntity;
        }

        /// <summary>
        /// 登出处理
        /// </summary>
        /// <param name="commandText"></param>
        /// <returns></returns>
        private static CommandResultEntity ExecuteLogoutCommand(string commandText, string remoteEndPoint)
        {
            CommandResultEntity resultEntity = new CommandResultEntity();
            resultEntity.CommandType = EnumDirectiveType.Logout;

            string username = commandText.Split(',')[0];
            var q = (from p in UserAccessTokenDB.DB where p.UserName == username select p).SingleOrDefault();
            if (q == null || q.RemoteEndPoint != remoteEndPoint)
            {
                resultEntity.Status = false;
                resultEntity.Message = "User Has Logout";
            }
            else
            {
                resultEntity.Status = true;
                resultEntity.Message = "Success";
                resultEntity.UserAccessToken = q;
            }

           
            return resultEntity;
        }
    }

    /// <summary>
    /// 命令执行结果实体
    /// </summary>
    public class CommandResultEntity
    {
        /// <summary>
        /// 命令类型
        /// </summary>
        public EnumDirectiveType CommandType { get; set; }
        /// <summary>
        /// 执行结果状态
        /// </summary>
        public bool Status { get; set; }
        /// <summary>
        /// 返回的结果信息
        /// </summary>
        public string Message { get; set; }
        /// <summary>
        /// 用户实体
        /// </summary>
        public UserAccessTokenEntity UserAccessToken { get; set; }

    }
}
